<?php

namespace App\Controller\InsideService;

use App\Constants\ErrorCode;
use App\Controller\AbstractController;
use Exception;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Guzzle\ClientFactory;

class BaseInside extends AbstractController {

    private string $url = '';
    protected string $code = '';

    /**
     * @Inject
     * @var ClientFactory
     */
    protected ClientFactory $clientFactory;

    public function __construct() {
        $gateway = config('apiadmin.gateway_ip');
        $this->url = "http://{$gateway}/sldnfInsideService/";
    }

    /**
     * 设置链接Code
     * @param string $code
     * @return BaseInside
     * @throws Exception
     */
    public function setCode(string $code): static {
        if (empty($code)) {
            throw new Exception("服务器获取异常");
        } else {
            $this->code = $code;

            return $this;
        }
    }

    public function getInfo($api, $params) {
        $client = $this->clientFactory->create(['verify' => false]);
        $response = $client->get($this->url . $api, [
            'query'   => $params,
            'headers' => [
                'Connection-Code' => $this->code
            ]
        ]);

        return json_decode($response->getBody()->getContents(), true);
    }

    public function postInfo($api, $data) {
        $client = $this->clientFactory->create(['verify' => false]);
        $response = $client->post($this->url . $api, [
            'form_params' => $data,
            'headers'     => [
                'Connection-Code' => $this->code
            ]
        ]);

        return json_decode($response->getBody()->getContents(), true);
    }

    /**
     * 成功的返回
     * @param array $data
     * @param string $msg
     * @param int $code
     * @return array
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    public function buildSuccess(array $data = [], string $msg = '操作成功', int $code = ErrorCode::SUCCESS): array {
        $return = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data
        ];
        if (env('APP_ENV', 'prod') === 'dev' && !empty($this->debug)) {
            $return['debug'] = $this->debug;
        }

        return $return;
    }

    /**
     * 错误的返回
     * @param int $code
     * @param string $msg
     * @param array $data
     * @return array
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    public function buildFailed(int $code, string $msg = '操作失败', array $data = []): array {
        $return = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data
        ];
        if (env('APP_ENV', 'prod') === 'dev' && !empty($this->debug)) {
            $return['debug'] = $this->debug;
        }

        return $return;
    }

}